//
//  CourseCenterCartViewController.m
//  xpkc
//
//  Created by TopSage iOS on 14/12/31.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "CourseCenterCartViewController.h"
#import "FMDatabase.h"
#import "CartModel.h"
#import "UserMessage.h"
@interface CourseCenterCartViewController ()
{
    NSMutableArray *dataArray;
    NSMutableArray * priceArray;
    NSMutableArray * idArray;
    NSMutableArray * binArray;
    CourseCenterCartView *CCCV;
    NSMutableIndexSet *selectIndexSet;
    NSString * str;
    
    NSMutableArray * _goodsArray;
    
    NSArray * _dataSource;
    
    double currenPrice;
    NSString * downStudycard;
    
    NSMutableArray * _selectArray;
}
@end

@implementation CourseCenterCartViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.navigationItem.title = @"购物车";
        [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                 [UIColor colorWithRed:255/255.0f green:159/255.f blue:0/255.f alpha:1], NSForegroundColorAttributeName,
                                                 nil] forState:UIControlStateSelected];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [CCCV.cartTable reloadData];
    [CCCV.totalPrice setNumerTo:0 animation:YES];
    [selectIndexSet removeAllIndexes];
    [_goodsArray removeAllObjects];
    [_selectArray removeAllObjects];
    [CCCV.payBtn setTitle:[NSString stringWithFormat:@"下订单(%@)",@"0"] forState:UIControlStateNormal];
    CCCV.payBtn.alpha = 0.6;
    CCCV.payBtn.userInteractionEnabled = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    dataArray = [NSMutableArray array];
    priceArray=[NSMutableArray array];
    idArray = [NSMutableArray array];
    binArray = [NSMutableArray array];
    _goodsArray = [NSMutableArray array];
    _selectArray = [NSMutableArray array];
    self.navigationController.navigationBar.hidden = NO;
    
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    [self getCartData];
    [self creatShopCartView];
    [self creatNavItem];
    [self getStudycard];
}

-(void)readData
{
    
    
    
    NSString *module = @"shopcar";
    NSString *interface = @"goodslist";
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid};
    NSLog(@"%@",parameter);
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSArray * arr =[dic objectForKey:@"goods_list"];
        
        
        _dataSource = [NSArray arrayWithArray:arr];
        
        for (NSDictionary * dic1 in arr) {
            NSString * str1 =[dic1 objectForKey:@"name"];
            [dataArray addObject:str1];
            NSString * str2 =[dic1 objectForKey:@"trueprice"];
            [priceArray addObject:str2];
            NSString * str3 =[NSString stringWithFormat:@"%@",[dic1 objectForKey:@"goods_id"]];
            [idArray addObject:str3];
            NSString * str4 =[NSString stringWithFormat:@"%@",[dic1 objectForKey:@"credits"]];
            [binArray addObject:str4];
        }
        
        [CCCV.cartTable reloadData];
           [hud hide:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           [hud hide:YES];
    }];
    

    
}

#pragma mark == creatview ==
- (void)creatNavItem{
    UIImage *backimg = [UIImage imageNamed:@"back1"];
    if (IsIOS7) {
        backimg = [backimg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *backitem = [[UIBarButtonItem alloc]initWithImage:backimg style:UIBarButtonItemStyleBordered target:self action:@selector(backToLastView)];
    self.navigationItem.leftBarButtonItem = backitem;
    if (_tmp == 1) {
        
    }else{
        UIBarButtonItem *shopitem = [[UIBarButtonItem alloc]initWithTitle:@"继续购物" style:UIBarButtonItemStyleBordered target:self action:@selector(backToLastView)];
        shopitem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = shopitem;
    }
    
}
/**
 *  创建购物车视图
 */
- (void)creatShopCartView{
    self.view.backgroundColor = [UIColor whiteColor];
    CCCV = [[CourseCenterCartView alloc]initWithFrame:self.view.bounds];
    CCCV.cartTable.delegate = self;
    CCCV.cartTable.dataSource = self;
    [CCCV.cartTable setEditing:YES animated:YES];
    [CCCV.totalPrice setNumerTo:999*4 animation:YES];
    [CCCV.selectAll addTarget:self action:@selector(selectAllCartItem:) forControlEvents:UIControlEventTouchUpInside];
    [CCCV.deleteBtn addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
    [CCCV.payBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:CCCV];
    [self updateCartItemsAndPrice];
    [self readData];
}

#pragma mark == func ==
- (void)backToLastView{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getCartData{
    selectIndexSet = [NSMutableIndexSet indexSet];
}

- (void)updateCartItemsAndPrice{
    __block int totalPrice = 0;
    [selectIndexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        
        totalPrice += [priceArray[idx] integerValue];
    }];
    currenPrice = totalPrice;
    [CCCV.totalPrice setNumerTo:totalPrice animation:YES];
    [CCCV.payBtn setTitle:[NSString stringWithFormat:@"下订单(%ld)",selectIndexSet.count] forState:UIControlStateNormal];
    if (selectIndexSet.count > 0) {
        CCCV.payBtn.alpha = 1;
        CCCV.payBtn.userInteractionEnabled = YES;
    }else{
        CCCV.payBtn.alpha = 0.6;
        CCCV.payBtn.userInteractionEnabled = NO;
    }
}
/**
 *  全选按钮
 *
 *  @param btn btn
 */
- (void)selectAllCartItem:(UIButton *)btn{
    if (btn.selected) {
        //取消全选
        for (int i = 0; i<dataArray.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [CCCV.cartTable deselectRowAtIndexPath:indexpath animated:YES];
        }
        [selectIndexSet removeAllIndexes];
        [_goodsArray removeAllObjects];
        [_selectArray removeAllObjects];
        btn.selected = NO;
    }else{
        [_goodsArray removeAllObjects];
        [_selectArray removeAllObjects];
        for (int i = 0; i<dataArray.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [CCCV.cartTable selectRowAtIndexPath:indexpath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            [selectIndexSet addIndex:i];
            
            
            CartModel * cartModel = [[CartModel alloc] init];
            
            cartModel.title = dataArray[i];
            cartModel.price = priceArray[i];
            cartModel.gold  = binArray[i];
            cartModel.quanID= idArray[i];
            [_goodsArray addObject:cartModel];
            
            
            NSDictionary * dict = _dataSource[i];
            
            [_selectArray addObject:dict];
            
            
        }
        btn.selected = YES;
    }
    [self updateCartItemsAndPrice];
    
    
}

- (void)deleteRow:(UIButton *)btn{
    [dataArray removeObjectsAtIndexes:selectIndexSet];
    
    NSMutableArray *deleteArray = [NSMutableArray array];
    [selectIndexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        

        NSString *module = @"shopcar";
        NSString *interface = @"goodsdel";
        NSString *timeString = [GetTime getTime];
        NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
        NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
        
        NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"aid":idArray[idx]};
        
        
        NSLog(@"%@",idArray);
        //POST请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
           
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        
        
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:idx inSection:0];
        [deleteArray addObject:indexpath];
        
        
    }];
    
    [CCCV.cartTable deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationFade];
    [selectIndexSet removeAllIndexes];
    CCCV.selectAll.selected = NO;
    [self updateCartItemsAndPrice];
    
}

//获取学习卡金额 传入下一个页面
-(void)getStudycard
{
   NSString *module = @"shopcar";
   NSString *interface = @"studycard";

   NSString *timeString = [GetTime getTime];
   NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
   NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];

   NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid};

   //POST请求
   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];

      if ([[dic objectForKey:@"succ"] isEqualToNumber:@1]) {
          
          downStudycard = [NSString stringWithFormat:@"%@",[dic objectForKey:@"info"]];
            }else{
            downStudycard=@"0";
        }

   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    downStudycard=@"0";
   }];

  
}



- (void)payBtnClick{
   
  
    logdebug(@"pay");
    CourseCenterOrderViewController *CCOVC = [[CourseCenterOrderViewController alloc]init];
    CCOVC.cartArray = _goodsArray;
    
    CCOVC.myCartArray = _selectArray;
    CCOVC.currenPrice = currenPrice;
    CCOVC.downStudycard=downStudycard;

    [self.navigationController pushViewController:CCOVC animated:YES];
}
#pragma mark -
#pragma mkar == tableview delegate ==
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataSource[indexPath.row];
    
    if (dic.count > 4) {
        
        NSArray * wardArray = dic[@"ward"];
        
        return  wardArray.count * 50 + 80 + 20;
        
    }
    return 80;
    
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseCenterCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[CourseCenterCartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    // NSLog(@"%@=======",dataArray[indexPath.row]);
    cell.itemTitle.text =dataArray[indexPath.row];
    //    cell.itemIntroduction.text = @"增：全程班 免费习题";
    //    cell.itemOriginalPrice.text = @"￥:9999";
    cell.itemPrice.text = [NSString stringWithFormat:@"￥%@",priceArray[indexPath.row]];
    
    NSDictionary * dic = _dataSource[indexPath.row];
    CGFloat offwidth = 0.04*SCREEN_WIDTH;
    
    CGFloat viewH = offwidth * 0.5 + 60;
    if (dic.count > 4) {
        
        NSArray * wardArray = dic[@"ward"];
        [cell configWithArray:wardArray];
        
//        cell.lineLabel.frame = CGRectMake(0, offwidth * 0.5 +60+10 + 60 * wardArray.count , SCREEN_WIDTH, 1);
        viewH += wardArray.count * 50 + 20;
    }else{
        
//        cell.lineLabel.frame = CGRectMake(0, offwidth * 0.5 +59, SCREEN_WIDTH - 50 , 1);
    }
    
    cell.lineLabel.frame = CGRectMake(0, viewH, SCREEN_WIDTH, 20);
    cell.lineLabel.backgroundColor = BGColor;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    logdebug(@"%d",indexPath.row);
    
    NSDictionary * dict = _dataSource[indexPath.row];
    
    str=dataArray[indexPath.row];
    [selectIndexSet addIndex:indexPath.row];
    [self updateCartItemsAndPrice];
    
    CartModel * model = [[CartModel alloc] init];
    model.title = dataArray[indexPath.row];
    model.price = priceArray[indexPath.row];
    model.gold=binArray[indexPath.row];
    model.quanID=idArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.editing) {
        [_goodsArray addObject:model];
        
        [_selectArray addObject:dict];
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    logdebug(@"%ld",indexPath.row);
    [selectIndexSet removeIndex:indexPath.row];
    [self updateCartItemsAndPrice];
    
    CartModel * model = [[CartModel alloc] init];
    
    model.title = dataArray[indexPath.row];
    model.price = priceArray[indexPath.row];
    model.gold=binArray[indexPath.row];
    model.quanID=idArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSDictionary * dict = _dataSource[indexPath.row];
    
    if (cell.editing) {
        [_goodsArray removeObject:model];
        
        
        [_selectArray removeObject:dict];
    }
}


#pragma mark == other ==
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
